import { useNavigate } from 'react-router-dom';
import type { DragEvent } from 'react';

export function useCategory (styles: CSSModuleClasses) {
  const navigate = useNavigate()
  const updateContentCategory = async (id: number, categoryId: number) => {
    await window.api.sql(
      'update contents set category_id=@categoryId where id=@id',
      'update',
      {
        id,
        categoryId,
      },
    )
    navigate(`/manager/category/contents/${categoryId}/content/${id}`)
  }

  const getDragHandlers = (categoryId: number) => {
    return {
      onDragOver: (e: DragEvent) => {
        e.preventDefault()
        e.currentTarget.classList.add(styles.dragging)
      },
      onDragLeave: (e: DragEvent) => {
        e.currentTarget.classList.remove(styles.dragging)
      },
      onDrop: (e: DragEvent) => {
        e.currentTarget.classList.remove(styles.dragging)
        const id = Number(e.dataTransfer.getData('id'))
        updateContentCategory(id, categoryId)
      },
    }
  }

  return {
    getDragHandlers,
  }
}